package cn.emall.order.service.impl;

import cn.emall.jedis.JedisClient;
import cn.emall.mapper.TbOrderItemMapper;
import cn.emall.mapper.TbOrderMapper;
import cn.emall.mapper.TbOrderShippingMapper;
import cn.emall.order.pojo.OrderInfo;
import cn.emall.order.service.OrderService;
import cn.emall.pojo.TbOrderItem;
import cn.emall.pojo.TbOrderShipping;
import cn.emall.utils.EmallResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 订单管理Service
 */
@Service
public class OrderServiceImpl implements OrderService{

    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private TbOrderShippingMapper tbOrderShippingMapper;
    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;
    @Autowired
    private JedisClient jedisClient;

    @Value("${ORDER_ID_GEN_KEY}")
    private String ORDER_ID_GEN_KEY;
    @Value("${ORDER_ID_START}")
    private String ORDER_ID_START;
    @Value("${ORDER_DETAIL_ID_GEN_KEY}")
    private String ORDER_DETAIL_ID_GEN_KEY;

    @Override
    public EmallResult createOrder(OrderInfo orderInfo) {
        //生成订单号,使用redis的incr方法生成
        if(!jedisClient.exists(ORDER_ID_GEN_KEY)){
            jedisClient.set(ORDER_ID_GEN_KEY,ORDER_ID_START);
        }
        String orderId = jedisClient.incr(ORDER_ID_GEN_KEY).toString();
        //补全OrderInfo的属性
        orderInfo.setOrderId(orderId);
        //1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
        orderInfo.setStatus(1);
        orderInfo.setCreateTime(new Date());
        orderInfo.setUpdateTime(new Date());
        //插入订单表
        tbOrderMapper.insert(orderInfo);
        //向订单明细表插入数据
        List<TbOrderItem> tbOrderItems = orderInfo.getOrderItems();
        for(TbOrderItem tbOrderItem : tbOrderItems){
            //生成明细的id,使用redis的incr方法生成
            String tbOrderItemId = jedisClient.incr(ORDER_DETAIL_ID_GEN_KEY).toString();
            //补全pojo属性
            tbOrderItem.setId(tbOrderItemId);
            tbOrderItem.setOrderId(orderId);
            //向明细表插入数据
            tbOrderItemMapper.insert(tbOrderItem);
        }
        //向订单物流插入数据
        TbOrderShipping tbOrderShipping = orderInfo.getOrderShipping();
        tbOrderShipping.setOrderId(orderId);
        tbOrderShipping.setCreated(new Date());
        tbOrderShipping.setUpdated(new Date());
        tbOrderShippingMapper.insert(tbOrderShipping);
        //返回EmallResult,包含订单号
        return EmallResult.ok(orderId);
    }
}
